using UnityEngine;
using System.Collections;

public class CompleteFadeIn : MonoBehaviour {

    private static bool ready;

    private static float currentValue = 0;

    private static float amount = 1f;

    private ArrayList fadeIn = new ArrayList();

	// Use this for initialization
	void Start () {
	
	}

    void Update()
    {
        if (ready)
        {
            currentValue += amount * Time.deltaTime;
            Fade(fadeIn, currentValue);


            if (currentValue >= 1)
            {
                ready = false;
                currentValue = 0;
                Fade(fadeIn, 1);
            }
        }
    }

    public void FadeIn(Transform target)
    {
        
        fadeIn.Clear();
        fadeIn.Add(target);

        foreach (Transform obj in target.transform)
        {
            Setup(fadeIn, obj);
        }

        ready = true;
    }

    private void Setup(ArrayList targetArray, Transform target)
    {
        targetArray.Add(target);

        foreach (Transform obj in target.transform)
        {
            Setup(targetArray, obj);
            targetArray.Add(obj);
        }
    }

    void Fade(ArrayList list, float i)
    {
        foreach (Transform obj in list)
        {
            if (obj)
            {
                if (obj.renderer)
                {

                    if (obj.renderer.material.color.a == 1)
                        return;

                    if (!obj.GetComponent<TextMesh>())
                    {
                        if (obj.renderer.material.shader != Shader.Find("Transparent/Diffuse"))
                            obj.renderer.material.shader = Shader.Find("Transparent/Diffuse");
                    }

                    obj.renderer.material.color = new Color(obj.renderer.material.color.r, obj.renderer.material.color.g, obj.renderer.material.color.b, i);
                }
            }
        }
    }
}
